<template>
  <div>

    <van-nav-bar
        title="支付订单"
        left-text="返回"
        right-text="新增地址"
        left-arrow
        @click-left="onClickLeft"
        @click-right="onClickRight"
    />
    <van-popup v-model="addrshow" position="top" :style="{ height: '30%' }">
      <div style="font-size:5vw;font-weight: 700; margin-top: 30px;margin-left: 140px;">
        <span>新增地址</span>
      </div>

      <van-cell-group class="addAddress">
        <van-field v-model="value" label="新增地址:" placeholder="请输入地址" />
      </van-cell-group>
      <van-button class="addressButton" icon="location-o" type="info" @click="addAddress(value)">
        添加
      </van-button>
    </van-popup>

    <van-notice-bar color="red" background="#ecf9ff" left-icon="volume-o">
      会员等级优惠：一级九八折！二级九五折！三级九折！四级八五折！五级七折！
    </van-notice-bar>

    <van-collapse v-model="activeNames">
    <van-collapse-item title="收获地址" name="1">

      <van-radio-group v-model="radio">
        <van-radio :name="addr.id" v-for="addr in addressList" :key="addr.id" @click="addrClick(addr.address)">
          <van-contact-card type="edit" :name="addr.address" :tel="addr.phone" :editable="false"/>
        </van-radio>
      </van-radio-group>

    </van-collapse-item>
    </van-collapse>

    <van-cell-group>
      <van-cell title="送达时间" value="尽快送达（送达时间16:30）" label="超时补偿⏰:超时赠送5元代金券" />
    </van-cell-group>

    <van-divider
        :style="{ color: 'black', borderColor: '#1989fa', padding: '0 16px' }"
    >
      订单信息
    </van-divider>

    <van-card
        :price="orders.price"
        :num="orders.goodsNum"
        :title="orders.name"
        :thumb="orders.imgUrl"
        v-for="orders in ordersList" :key="orders.id"
    />

    <van-cell-group>
      <van-cell title="订单实际金额:">{{this.$route.params.cartsTotal.toFixed(2)}}元</van-cell>
    </van-cell-group>
    <van-cell>您已达到满{{this.couponPrice}}元减<span style="color: red">{{this.numPrice}}</span>元</van-cell>

    <van-submit-bar button-text="立即支付" @submit="showPopup">实际支付:<span>{{this.actualPrice}}</span>元</van-submit-bar>


    <van-cell-group>
      <van-cell title="会员等级:">
        <van-rate icon="like" void-icon="like-o" v-model="this.level" />
      </van-cell>
    </van-cell-group>

    <van-divider /><van-divider /><van-divider /><van-divider /><van-divider /><van-divider /><van-divider /><van-divider />

    <!-- 付款弹窗 -->
    <div class="pay-panel">
      <van-popup v-model="isShow"  get-container="#app-container" closeable close-icon-position="top-left" position="bottom" :style="{ height: '60%' }">
        <div class="pay-title">确认付款</div>
        <p class="pay-amount">{{this.actualPrice}}元</p>
        <van-cell-group>
          <van-cell title="订单信息" value="蜗牛生鲜订单" />
          <van-cell title="付款方式" @click="showPay" :value="this.payValue" is-link />
          <van-action-sheet v-model="show" :actions="actions" @select="onSelect"/>

          <!-- 密码输入框 -->
          <van-password-input
              :value="value"
              :focused="showKeyboard"
              @focus="showKeyboard = true"
          />
          <!-- 数字键盘 -->
          <van-number-keyboard
              v-model="value"
              :show="showKeyboard"
              @blur="showKeyboard = false"
          />

        </van-cell-group>
        <div class="pay-button"  @click="paySuccess">
          <van-button type="info" size="large">立即付款</van-button>
        </div>
      </van-popup>


    </div>


  </div>
</template>

<script>
import 'vant/lib/index.css';
import { ContactCard,NavBar,Divider} from 'vant';
import { Collapse, CollapseItem,Cell,CellGroup,Card} from 'vant';
import { RadioGroup, Radio} from 'vant';
import { SubmitBar } from 'vant';
import { Popup } from 'vant';
import { Button } from 'vant';
import { Rate } from 'vant';
import { NoticeBar } from 'vant';
import { ActionSheet } from 'vant';
import { Loading } from 'vant';
import { Toast } from 'vant';
import { PasswordInput, NumberKeyboard } from 'vant';
import { Field } from 'vant';
export default {
  components: {
    [ContactCard.name]: ContactCard,
    [NavBar.name]: NavBar,
    [Divider.name]: Divider,
    [Collapse.name]: Collapse,
    [CollapseItem.name]: CollapseItem,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Card.name]: Card,
    [SubmitBar.name]: SubmitBar,
    [Popup.name]: Popup,
    [Button.name]: Button,
    [Rate.name]: Rate,
    [NoticeBar.name]: NoticeBar,
    [ActionSheet.name]: ActionSheet,
    [Loading.name]: Loading,
    [PasswordInput.name]: PasswordInput,
    [NumberKeyboard.name]: NumberKeyboard,
    [Toast.name]: Toast,
    [Field.name]: Field,
  },
  data() {
    return {
      addrshow:false,
      value: '',
      showKeyboard: false,
      activeNames: [''],
      radio:'1',
      isShow: false,
      show:false,
      payValue:'',
      actions: [{ name: '支付宝支付' }, { name: '微信支付' }],
      ordersList: [],
      addressList: [],
       //优惠券金额
      couponPriceArray:[39,59,79,99],
      couponPrice:0,
      //优惠金额
      numPrice:0,
      //实际支付
      actualPrice:0,
      //用户等级
      level:0,
      //打折数额
      levelArray:0,
      //收货地址
      userAddress:''
    }
  },
  methods: {
    onClickRight(){
    this.addrshow=true;
    },
    onClickLeft() {
      let id=this.$route.params.oderId;
      this.$axios.get('/api/app/deleteOrdersById?id='+id)
          .then(res=>{
            console.log(res.data)
            if(res.data.code==200){
              Toast.fail('订单已失效');
            }
          }),
          this.$axios.get('/api/app/deleteOrdersDetail?id='+id)
              .then(res=>{
                if(res.data.code==200){
                console.log(res.data)
                }
              })
        this.$router.push('carts');

    },
    updateCount(){
      let ordersDetailsList=this.ordersList;
      this.$axios.post('api/app/updateCount',ordersDetailsList)
          .then(res=>{
            if(res.data.code==200){
              console.log(res.data)
            }
          })
    },

    addAddress(addr){
      console.log(addr);
      let phone = sessionStorage.getItem("phone");
      let address={};
      address.phone=phone;
      address.address=addr;
      this.$axios.post('api/app/address/saveAddress',address)
          .then(res=>{
          if(res.data.code==200){
            Toast.success('添加成功');
            this.addrshow=false;
            this.queryAddressByPhone()
          }
    })
    },
    addrClick(item){
      this.userAddress=item;
    },
    onSelect(item) {
      // 默认情况下点击选项时不会自动收起
      // 可以通过 close-on-click-action 属性开启自动收起
      this.show = false;
      this.payValue=item.name;

    },
    showPay(){
      this.show=true;
    },
    showPopup() {
      this.isShow = true;
    },
    queryUserLevel(){
      let phone = sessionStorage.getItem("phone");
      this.$axios.get('api/app/queryUserLevel?phone='+phone)
      .then(res=>{
        console.log(res.data)
        if(res.data.code==200){
          this.level=res.data.data.levels
          console.log("会员等级"+this.level)
          if(this.level==0){
            this.levelArray=1
          }else if(this.level==1){
            this.levelArray=0.98
          }else if(this.level==2){
            this.levelArray=0.95
          }else if(this.level==3){
            this.levelArray=0.90
          }else if(this.level==4){
            this.levelArray=0.85
          }else if(this.level==5){
            this.levelArray=0.7
          }
          this.actualPrice=((this.$route.params.cartsTotal-this.numPrice)* this.levelArray).toFixed(2);
          console.log("会员："+this.actualPrice)

        }
      })
    },
    queryOrdersDetails() {
      let ordersId = this.$route.params.oderId;
      console.log("订单id" + ordersId);
      this.$axios.get('api/app/getAllOrdersDetails?ordersId=' + ordersId)
          .then(res => {
            console.log(res.data)
            if (res.data.code == 200) {
              this.ordersList = res.data.data;
              console.log(this.ordersList);
            }
          })
    },
    queryAddressByPhone() {
      let phone = sessionStorage.getItem("phone");
      this.$axios.get('api/app/address/queryAddressByPhone?phone=' + phone)
          .then(res => {
            console.log(res.data)
            if (res.data.code == 200) {
              // console.log(ref.data)
              this.addressList = res.data.data;
            }
          })
    },

    updatePaySuccess(){
      let orders={};
      orders.payMethod=this.payValue;
      orders.actualAmount=this.actualPrice;
      orders.address=this.userAddress;
      orders.id=this.$route.params.oderId;
      this.$axios.post('/api/app/updatePaySuccess',orders)
          .then(res=>{
            console.log(res.data)
            if(res.data.code==200){
              Toast.success('购买成功');
            }
          })
    },
    paySuccess(){
      this.isShow=false;
      const toast1 =  Toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner',
      });
       this.updatePaySuccess();
       this.updateCount();
      this.$router.push({name:'orderDetails',
        params:{"address":this.userAddress,
          "actualPrice":this.actualPrice,
          "ordersId":this.$route.params.oderId}})
    }
  },
    created() {
      this.$route.params.oderId;
      console.log(this.$route.params.oderId);
      let cartsTotal=this.$route.params.cartsTotal;
      console.log("总价:"+cartsTotal);
      let arr = this.couponPriceArray;
      for (let i = 0; i < arr.length; i++) {
        if(cartsTotal <= arr[i]){
          this.couponPrice=arr[i-1]
          break;
        }
      }

      if(this.couponPrice==39){
        this.numPrice=2
      }else if(this.couponPrice==59){
        this.numPrice=5
      }else if(this.couponPrice==79){
        this.numPrice=8
      }else if(this.couponPrice==99){
        this.numPrice=15
      }
      console.log("优惠券价："+this.couponPrice)
      console.log("优惠:"+this.numPrice)
      this.queryOrdersDetails()
      this.queryAddressByPhone()
      this.queryUserLevel()
    }
}
</script>

<style lang="less" scoped>

.van-submit-bar{
  bottom: 50px
}

/deep/.van-radio__label{
  flex:1;
}
.pay-title {
  height: 50px;
  background-color: whitesmoke;
  line-height: 50px;
  text-align: center;
}

.pay-panel {
  font-family: "Microsoft YaHei";
}

.pay-amount {
  height: 50px;
  line-height: 50px;
  text-align: center;
  font-size: 40px;
}

.pay-button {
  margin-top: 20px;
  padding: 0 20px;
  display: flex;
  justify-content: center;
}
.addAddress{
  margin-top: 40px;
}
.addressButton{
  margin-top: 20px;
  margin-left: 140px;
}
</style>